//index.js
//获取应用实例
const app = getApp()
const APP_ID = 'wxeb7a5c3c7e80e72b';//输入小程序appid  
const APP_SECRET = '1c7a5dfa70757926dcd2b2f09428b88f';//输入小程序app_secret
var OPEN_ID = ''//储存获取到openid  
var SESSION_KEY = ''//储存获取到session_key
var CODE = ''

var timeoutDrag = '';
var dragIsFun = true;
const ajax = require('./js/ajax.js')

Page({
  data: {
    appid: "",
    session_key: '',

    pubFiles:[],
    priPaperFiles: [],
    iconList:[],

    menuShow:false,
    menuX:0,
    menuY:0,
    canvasIndex:0,

    canvasTextList:[],
    canvasImgList:[],
    canvasTextKey: 0,
    canvasImgKey:0,
    widthCache:50,
    heightCache:50,

    dataAnimation: {},
    wHSHow: false,
    menuType: '',
    textListAnimation: {},
    textListSHow: false,
    menuType:'',

    img: "",
    imgUrl: "",
    pictureProportion: '',
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad(options) {
    console.log(wx,'--1--');
    let that = this;
    // 登录
    // wx.login({
    //   success: res => {
    //     console.log(res, '--login--')
    //     wx.request({
    //       //获取openid接口  
    //       url: 'https://api.weixin.qq.com/sns/jscode2session',
    //       data: {
    //         appid: APP_ID,
    //         secret: APP_SECRET,
    //         js_code: res.code,
    //         grant_type: 'authorization_code'
    //       },
    //       method: 'GET',
    //       success: function (res) {
    //         console.log(res.data, '---ss-----')
    //         OPEN_ID = res.data.openid;//获取到的openid
    //         SESSION_KEY = res.data.session_key;//获取到session_key
    //         that.setData({
    //           openid: res.data.openid.substr(0, 10) + '********' + res.data.openid.substr(res.data.openid.length - 8, res.data.openid.length),
    //           session_key: res.data.session_key.substr(0, 8) + '********' + res.data.session_key.substr(res.data.session_key.length - 6, res.data.session_key.length)
    //         })
    //       }
    //     })
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //   }
    // })

    ajax.ajax_get(
      'http://47.99.174.254:8790/zone/pubFiles',
      {},
      data => {
        console.log(data, '========================')
        this.setData({
          pubFiles: data,
        })
      }
    )
    ajax.ajax_get(
      'http://47.99.174.254:8790/zone/priPaperFiles',
      {},
      data => {
        console.log(data, '========================')
        that.data.imgUrl = data[0].key;
        this.setData({
          priPaperFiles: data,
          imgUrl: that.data.imgUrl,
        })
        wx.downloadFile({
          url: that.data.imgUrl,
          success: function (res) {
            console.log(res, '-----success-----');
            that.setData({
              img: res.tempFilePath
            });
            wx.getImageInfo({
              src: res.tempFilePath,
              success: function (res) {
                that.canvasImg(res);
              }
            })
          },
          fail: function (res) {
            console.log(res, '----fail------')
          }
        })
      }
    )
    ajax.ajax_get(
      'http://47.99.174.254:8790/zone/priMaterialFiles',
      {},
      data => {
        console.log(data, '========================')
        this.setData({
          iconList: data,
        })
      }
    )
  },
  //事件处理函数
  canvasImg(res) {
    let that = this;
    let width, height;
    that.data.pictureProportion = res.height / res.width;
    let obj = wx.createSelectorQuery();
    obj.select('.myCanvas').boundingClientRect(function (rect) {
      width = rect.width;
      height = rect.width * that.data.pictureProportion;
      console.log('--',height)
      const ctx = wx.createCanvasContext('myCanvas');
      // that.data.img.onload = function () {
      ctx.drawImage(that.data.img, 0, 0, width, height);   //里面的参数无非就是图片放置的位置即图片的横纵坐标，图片的宽高
      // }
      console.log(that.data.img, 0, 0, width, height, '--2--')
      ctx.draw();
    }).exec();
  }, 
  saveImg() {
    let that = this;
    let obj = wx.createSelectorQuery();
    obj.select('.myCanvas').boundingClientRect(function (rect) {
      const ctx = wx.createCanvasContext('myCanvas');
      ctx.setFillStyle("#000");
      ctx.font = "16px 微软雅黑";                             //字大小
      ctx.setTextAlign('left');                        //是否居中显示，参考点画布中线
      for (let d of that.data.canvasTextList) {
        that.writeTextOnCanvas(ctx, 20, (parseInt(d.width) -20 ) / 750 * wx.getSystemInfoSync().windowWidth, d.x + 5, d.y + 5,d.text)
        // ctx.fillText(d.text, d.x + 5, d.y + 25); 
        //150:canvas画布宽300，取1/2，中间，280：纵向位置
      }
      let imgsrc;
      let i = 0;
      if (that.data.canvasImgList.length > 0){

        for (let d of that.data.canvasImgList) {
          wx.downloadFile({
            url: d.src,
            success: function (res) {
              imgsrc = res.tempFilePath;
              wx.getImageInfo({
                src: imgsrc,
                success: function (res) {
                  ctx.drawImage(imgsrc, d.x, d.y, parseInt(d.width) / 750 * wx.getSystemInfoSync().windowWidth, parseInt(d.width) * (res.height / res.width) / 750 * wx.getSystemInfoSync().windowWidth);
                  i++;
                  if (i == that.data.canvasImgList.length) {
                    ctx.draw(true);
                    saveImgFun();
                  }
                }
              })
            },
            fail: function (res) {
              console.log('fail-------------', res)
              if (res.errMsg == 'downloadFile:fail downloadFile protocol must be http or https') {
                wx.getImageInfo({
                  src: d.src,
                  success: function (res) {
                    ctx.drawImage(d.src, d.x, d.y, parseInt(d.width) / 750 * wx.getSystemInfoSync().windowWidth, parseInt(d.width) * (res.height / res.width) / 750 * wx.getSystemInfoSync().windowWidth);
                    i++;
                    if (i == that.data.canvasImgList.length) {
                      ctx.draw(true);
                      saveImgFun();
                    }
                  }
                })
              }
            }
          })
        }
      }else{
        ctx.draw(true);
        saveImgFun();
      }
      function saveImgFun(){
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          canvasId: 'myCanvas',
          success: function (res) {
            console.log(res.tempFilePath) //生成的临时图片路径
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                console.log(res);
                wx.showToast({
                  title: '保存成功',
                })
              }
            })
          }
        })
      }
    }).exec();
  },
  EventHandleStart: function(e) {
    console.log(e)
  },
  closeTextData(e) {
    if (this.data.wHSHow){
      const animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      })
      this.dataAnimation = animation
      animation.translate(0, 0).step()
      this.setData({
        dataAnimation: animation.export(),
        wHSHow:false,
      })
    }
    for (let d of this.data.canvasTextList) {
      d.focus = false;
    }
    this.setData({
      canvasTextList: this.data.canvasTextList
    })
  },
  menu(e){
    console.log(e,'----------')
    this.setData({
      menuShow: true,
      menuX: e.detail.x,
      menuY: e.detail.y,
    })
  },
  menubgTap(){
    this.setData({
      menuShow: false
    })
    let that = this;
    wx.getImageInfo({
      src: that.data.img,
      success: function (res) {
        that.canvasImg(res);
      }
    })
  },
  setBG(e){
    let that = this;
    let imgurl = e.currentTarget.dataset['imgurl'];
    wx.downloadFile({
      url: imgurl,
      success: function (res) {
        that.setData({
          img: res.tempFilePath,
        });
        wx.getImageInfo({
          src: res.tempFilePath,
          success: function (res) {
            console.log(res, '--1--')
            that.canvasImg(res);
          }
        })
      },
    })
  },
  addIcon(e) {
    let index = e.currentTarget.dataset['index'];
    let that = this;
    this.data.canvasImgList.push({
      key: this.data.canvasImgKey,
      src: this.data.iconList[index].key,
      x: 0,
      y: 0,
      width: '100rpx',
    });

    that.setData({
      canvasImgKey: this.data.canvasImgKey++,
      canvasImgList: this.data.canvasImgList,
    })
  },
  upBgImg(){
    let that = this;
    wx.chooseImage({
      count: 1,  //最多可以选择的图片总数  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        console.log(res)
        let imgUrl = res.tempFilePaths[0];
        if (that.data.menuType == 'bg') {
          that.setData({
            img: imgUrl
          });
          wx.getImageInfo({
            src: res.tempFilePaths[0],
            success: function (res) {
              that.canvasImg(res);
            }
          })
        } else {
          that.data.canvasImgList.push({
            key: that.data.canvasImgKey,
            src: imgUrl,
            x: 0,
            y: 0,
            width: '100rpx',
          });
          that.setData({
            canvasImgKey: that.data.canvasImgKey++,
            canvasImgList: that.data.canvasImgList,
          })
        }
      },
    })
  },
  insertText(){
    let that = this;
    that.setData({
      menuShow: false,
    })
    for (let d of this.data.canvasTextList) {
      d.focus = false;
    }
    this.data.canvasTextList.push({
      key: this.data.canvasTextKey,
      text:'',
      focus:true,
      x: 100,
      y: 50,
      width:'200rpx',
      height:'100rpx',
      cursorTop: '0',
      cursorLeft: '0',
    });

    that.setData({
      canvasTextKey: this.data.canvasTextKey++,
      canvasTextList: this.data.canvasTextList,
    })
  },
  canvasTextFocus(e) {
    let index = e.currentTarget.dataset['index'];
    this.setData({
      ['canvasTextList[' + index + '].text']: e.detail.value,
      // ['canvasTextList[' + index + '].cursorTop']: e.detail.value,
      // ['canvasTextList[' + index + '].cursorLeft']: ((e.detail.value.length * 16) % canvasTextList[index].width) + 'px',
    })
  },
  textTap(e){
    let that = this; 
    let index = e.currentTarget.dataset['index'];
    const animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.dataAnimation = animation
    animation.translate(0, 40).step()

    if (e.currentTarget.dataset['type'] == 'text') {
      for (let d of this.data.canvasTextList) {
        d.focus = false;
      }
      this.data.canvasTextList[index].focus = true;
      this.setData({
        canvasTextList: this.data.canvasTextList,
        widthCache: parseInt(this.data.canvasTextList[index].width),
        heightCache: parseInt(this.data.canvasTextList[index].height),
        dataAnimation: animation.export(),
        canvasIndex: index,
        wHSHow: true,
        menuType:'text',
      })
    } else {
      this.setData({
        canvasImgList: this.data.canvasImgList,
        widthCache: parseInt(this.data.canvasImgList[index].width),
        heightCache: parseInt(this.data.canvasImgList[index].height),
        dataAnimation: animation.export(),
        canvasIndex: index,
        wHSHow: true,
        menuType: 'icon',
      })
    }
  },
  textTapEnd(e){
    let that = this;
    let index = e.currentTarget.dataset['index'];
  },
  drag(e){
    let that = this;
    let index = e.currentTarget.dataset['index'];
    if (dragIsFun){
      dragIsFun = false;
      if (e.currentTarget.dataset['type'] == 'text'){
        that.setData({
          ['canvasTextList[' + index + '].focus']: false,
        })
      }else{
        that.setData({
          ['canvasImgList[' + index + '].focus']: false,
        })
      }
    }
    clearTimeout(timeoutDrag);
    timeoutDrag = setTimeout(function () {
      if (e.currentTarget.dataset['type'] == 'text') {
        that.setData({
          canvasTextList: that.data.canvasTextList,
          ['canvasTextList[' + index + '].x']: e.detail.x,
          ['canvasTextList[' + index + '].y']: e.detail.y,
        })
      }else{
        that.setData({
          canvasTextList: that.data.canvasTextList,
          ['canvasImgList[' + index + '].x']: e.detail.x,
          ['canvasImgList[' + index + '].y']: e.detail.y,
        })
      }
      dragIsFun = true;
    },300)
  },
  // dragEnd(e) {
  //   console.log(e,'--2--')
  // },

  widthChange(e) {
    if (this.data.menuType == 'text'){
      this.setData({
        widthCache: e.detail.value,
        ['canvasTextList[' + this.data.canvasIndex + '].width']: e.detail.value + 'rpx'
      })
    }else{
      this.setData({
        widthCache: e.detail.value,
        ['canvasImgList[' + this.data.canvasIndex + '].width']: e.detail.value + 'rpx'
      })
    }
  },
  heightChange(e) {
    if (this.data.menuType == 'text') {
      this.setData({
        heightCache: e.detail.value,
        ['canvasTextList[' + this.data.canvasIndex + '].height']: e.detail.value+'rpx'
      })
    }else{
      this.setData({
        heightCache: e.detail.value,
        ['canvasImgList[' + this.data.canvasIndex + '].height']: e.detail.value + 'rpx'
      })
    }
  },
  delText(){
    if (this.data.menuType == 'text') {
      console.log(this.data.canvasTextList, this.data.canvasIndex,'---1--')
      this.data.canvasTextList.splice(this.data.canvasIndex, 1);
      this.setData({
        canvasTextList: this.data.canvasTextList
      })
      console.log(this.data.canvasTextList, this.data.canvasIndex, '---2--')
    }else{
      this.data.canvasImgList.splice(this.data.canvasIndex, 1);
      this.setData({
        canvasImgList: this.data.canvasImgList
      })
    }
    if (this.data.wHSHow) {
      const animation = wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      })
      this.dataAnimation = animation
      animation.translate(0, 0).step()
      this.setData({
        dataAnimation: animation.export(),
        wHSHow: false,
      })
    }
  },
  openBG(e){
    let that = this;
    const animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.textListAnimation = animation;
    let textListSHow = true;
    if (this.data.menuType == 'bg') {
      if (this.data.textListSHow) {
        animation.bottom(0).opacity(0).step();
        textListSHow = false;
      }else{
        animation.bottom(60).opacity(1).step();
      }
      this.setData({
        textListAnimation: animation.export(),
        textListSHow: textListSHow,
      })
    } else {
      if (this.data.textListSHow) {
        this.setData({
          menuType: 'bg',
        })
      } else {
        animation.bottom(60).opacity(1).step()
        this.setData({
          textListAnimation: animation.export(),
          textListSHow: textListSHow,
          menuType: 'bg',
        })
      }
    }
  },
  openIcon(e){
    let that = this;
    const animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.textListAnimation = animation;
    let textListSHow = true;
    if (this.data.menuType == 'icon') {
      if (this.data.textListSHow) {
        animation.bottom(0).opacity(0).step()
          textListSHow = false;
      } else {
        animation.bottom(60).opacity(1).step()
      }
      this.setData({
        textListAnimation: animation.export(),
        textListSHow: textListSHow,
      })
    }else{
      if (this.data.textListSHow) {
        this.setData({
          menuType: 'icon',
        })
      } else {
        animation.bottom(60).opacity(1).step()
        this.setData({
          textListAnimation: animation.export(),
          textListSHow: textListSHow,
          menuType: 'icon',
        })
      }
    }
  },

  writeTextOnCanvas(ctx,lineHeight, rw,x,y, text){
    // var c = document.getElementById("canvas");
    // var context = c.getContext("2d");
    var chr = text.split("");
    var temp = "";
    var row = [];

    for (var a = 0; a < chr.length; a++) {
      if (ctx.measureText(temp).width < rw) {
        console.log(ctx.measureText(temp).width,'----------',rw)
      } else {
        row.push(temp);
        temp = "";
      }
      temp += chr[a];
    }
    row.push(temp);

    for (var b = 0; b < row.length; b++) {
      ctx.fillText(row[b], x, y + (b + 1) * lineHeight);
    }
  }
})
